package com.liuc.practice.bank.transfer.factory;

import com.liuc.practice.bank.transfer.annotation.Autowired;
import com.liuc.practice.bank.transfer.annotation.Service;
import com.liuc.practice.bank.transfer.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author Liu Chang
 * @Date 2021/3/11 10:29 下午
 */
@Service(value = "proxyFactory")
public class ProxyFactory {

    @Autowired
    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public Object getJdkProxyObject(Object object) {
        return Proxy.newProxyInstance(object.getClass().getClassLoader(),
                object.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object result = null;
                        transactionManager.openTransaction();

                        try {
                            result = method.invoke(object, args);
                            transactionManager.commit();
                        } catch (Exception e) {
                            transactionManager.rollback();
                            throw new Exception("事务回滚，异常抛出");
                        }


                        return result;
                    }
                });
    }

    public Object getCGLibProxyObject(Object obj) {
        return Enhancer.create(obj.getClass(), new MethodInterceptor() {

            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object obj = null;

                try {
                    transactionManager.openTransaction();
                    obj = method.invoke(obj, objects);
                    transactionManager.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    transactionManager.rollback();
                    throw e;
                }
                return obj;
            }
        });
    }
}
